//
//  FindDetailViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/9.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "FindDetailViewController.h"
#import "FindTableViewCell.h"
#import "LoginViewController.h"
#import "ZanListViewController.h"
#import "FindMeViewController.h"

#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "UIImageView+LK.h"
#import "FindCommentTableViewCell.h"
#import "CommonService.h"

#import "UserEntity.h"
#import "CommentEntity.h"
#import "LPUtils.h"
#import "MJRefresh.h"
#import "ReportViewController.h"
#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

@interface FindDetailViewController ()<UITextFieldDelegate, FindDelegate,UIAlertViewDelegate> {
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int page;
}

@property (nonatomic, strong) NSMutableArray *mutableArrayComment;
@property (nonatomic, strong) IBOutlet UITableView *tableViewContent;
@property (nonatomic, strong) IBOutlet UITextField *textFieldComment;
@property (nonatomic, strong) IBOutlet UIView *viewComment;

@property (nonatomic, strong) IBOutlet UIButton *btnSend;
@property (nonatomic, strong) UIImageView *imageViewBackground;

@end

@implementation FindDetailViewController
@synthesize mutableArrayComment, tableViewContent;
@synthesize findEntity;
@synthesize textFieldComment, btnSend, viewComment;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"发现详情";
    page = 1;
    
    mutableArrayComment = [[NSMutableArray alloc] init];
    
    textFieldComment.delegate = self;
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    
    [btnSend.layer setMasksToBounds:YES];
    [btnSend.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    
    [self addHeader];
    [self addFooter];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    } else {
        return [mutableArrayComment count];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        static NSString *couponTableViewCellIdentifier=@"FindTableViewCell";
        FindTableViewCell *cell = (FindTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
            cell.delegate = self;
        }

        [cell setFindEntity:findEntity];
        cell.labelComment.text = findEntity.commentCount;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *insertTime = [dateFormatter dateFromString:findEntity.insert_time];
        NSString *time = [LPUtils compareCurrentTime:insertTime];
        cell.labelTimer.text = time;
        
        cell.labelTouristSpotName.text = findEntity.content;
        cell.labelTouristSpotName.numberOfLines = 0;
        [cell.labelTouristSpotName sizeThatFits:CGSizeMake(SCREEN_WIDTH - 33, MAXFLOAT)];
        cell.labelTraveller.text = findEntity.nickname;
        [cell.btnZanTotal setTitle:findEntity.good forState:UIControlStateNormal];
        [cell.btnZanTotal.layer setMasksToBounds:YES];
        [cell.btnZanTotal.layer setCornerRadius:10.0]; //设置矩形四个圆角半径
        
        [cell.btnAuthor sd_setImageWithURL:[NSURL URLWithString:findEntity.userAlbum] forState:UIControlStateNormal];
        [cell.btnAuthor.layer setMasksToBounds:YES];
        [cell.btnAuthor.layer setCornerRadius:20.0]; //设置矩形四个圆角半径
        cell.btnAuthor.tag = [findEntity.userid intValue];
        cell.btnAddGZ.tag = [findEntity.userid intValue];
        if ([findEntity.goodflag isEqualToString:@"1"] == YES) {
            [cell.btnZan setBackgroundImage:[UIImage imageNamed:@"发现_03_02"] forState:UIControlStateNormal];
            [cell.btnZanTitle setTitle:@"已赞" forState:UIControlStateNormal];
        } else {
            [cell.btnZan setBackgroundImage:[UIImage imageNamed:@"发现_03"] forState:UIControlStateNormal];
            [cell.btnZanTitle setTitle:@"赞" forState:UIControlStateNormal];
        }
        if (![findEntity.userid isEqualToString:[UserEntity sharedInstance].userId])
        {
        if ([[NSString stringWithFormat:@"%@",findEntity.followed]isEqualToString:@"1"]) {
            cell.btnAddGZ.hidden = YES;
            cell.labelTimer.hidden = NO;
        } else {
            cell.btnAddGZ.hidden = NO;
            cell.labelTimer.hidden = YES;
        }
        }
        NSArray *arrayBtn = [[NSArray alloc] initWithObjects:cell.btnZan1,cell.btnZan2,cell.btnZan3,cell.btnZan4,cell.btnZan5,cell.btnZan6,nil];;
        for (int i = 0; i < [findEntity.mutableArrayUser count] && i < 6; i++) {
            UserEntity *userEntity = [findEntity.mutableArrayUser objectAtIndex:i];
            UIButton *btn = arrayBtn[i];
            btn.hidden = NO;
            btn.tag = [userEntity.userId intValue];
            [btn sd_setImageWithURL:[NSURL URLWithString:userEntity.userAlbum] forState:UIControlStateNormal];
            [btn.layer setMasksToBounds:YES];
            [btn.layer setCornerRadius:17.0]; //设置矩形四个圆角半径
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        static NSString *couponTableViewCellIdentifier=@"FindCommentTableViewCell";
        FindCommentTableViewCell *cell = (FindCommentTableViewCell *)[tableView dequeueReusableCellWithIdentifier:couponTableViewCellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"FindCommentTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        
        if ([mutableArrayComment count] < indexPath.row + 1) {
            return nil;
        }
        
        CommentEntity *entity = [mutableArrayComment objectAtIndex:indexPath.row];
        [cell.imageViewHeader sd_setImageWithURL:[NSURL URLWithString:entity.userAlbum]];
        [cell.imageViewHeader.layer setMasksToBounds:YES];
        [cell.imageViewHeader.layer setCornerRadius:20.0]; //设置矩形四个圆角半径
        
        cell.deleteBtn.tag = indexPath.row;
        if ([entity.userid isEqualToString:USERID])
        {
            cell.deleteBtn.hidden = NO;
            [cell.deleteBtn addTarget:self action:@selector(deleteComment:) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
            cell.deleteBtn.hidden = YES;
        }

        
        cell.labelName.text = entity.nickname;
        cell.labelContent.text = entity.content;
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *insertTime = [dateFormatter dateFromString:entity.insert_time];
        NSString *time = [LPUtils compareCurrentTime:insertTime];
        cell.labelTime.text = time;
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        if (findEntity.img_height_ == nil) {
            FindEntity *entity = findEntity;
            //评价高度自适应
            UIFont *font = [UIFont fontWithName:@"Arial" size:13];
            //设置一个行高上限
            CGSize size = CGSizeMake(ScreenWidth - 33,1000);
            //计算实际frame大小，并将label的frame变成实际大小
            CGSize labelsize = [entity.content sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
            
            NSArray *widthArray = [entity.img_width componentsSeparatedByString:@","];
            NSArray *heightArray = [entity.img_height componentsSeparatedByString:@","];
            
            CGFloat totalHeight = -2;
            for (int i = 0; i < [widthArray count]; i ++)
            {
                CGFloat width = [[widthArray objectAtIndex:i] floatValue];
                CGFloat height = [[heightArray objectAtIndex:i] floatValue];
                totalHeight += (SCREEN_WIDTH - 8)*height/width + 2;
            }
            
            CGFloat height =  totalHeight + 170 + labelsize.height;
            DebugLog(@"height = %f, index = %ld", height, (long)indexPath.row);
            
            return height;
        } else {
            FindEntity *entity = findEntity;
            //评价高度自适应
            UIFont *font = [UIFont fontWithName:@"Arial" size:13];
            //设置一个行高上限
            CGSize size = CGSizeMake(ScreenWidth - 33,1000);
            //计算实际frame大小，并将label的frame变成实际大小
            CGSize labelsize = [entity.content sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
            
            NSArray *widthArray = [entity.img_width_ componentsSeparatedByString:@","];
            NSArray *heightArray = [entity.img_height_ componentsSeparatedByString:@","];

            CGFloat totalHeight = -2;
            for (int i = 0; i < [widthArray count]; i ++)
            {
                CGFloat width = [[widthArray objectAtIndex:i] floatValue];
                CGFloat height = [[heightArray objectAtIndex:i] floatValue];
                totalHeight += (SCREEN_WIDTH - 8)*height/width + 2;
            }

            CGFloat height =  totalHeight + 170 + labelsize.height;
            DebugLog(@"height = %f, index = %ld", height, (long)indexPath.row);
           
            return height;
        }
    } else {
        return 75;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if(section == 1){
        
        UIView *headerView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 50, 30)];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:14];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor lightGrayColor];
        label.text = [NSString stringWithFormat:@"评论"];
        
        UILabel *labelTotalComment = [[UILabel alloc] initWithFrame:CGRectMake(250, 0, 60, 30)];
        labelTotalComment.backgroundColor = [UIColor clearColor];
        labelTotalComment.font = [UIFont boldSystemFontOfSize:13];
        labelTotalComment.textAlignment = NSTextAlignmentRight;
        labelTotalComment.textColor = [UIColor colorWithRed:0.55 green:0.77 blue:0.2 alpha:1];
        int count = (int)[mutableArrayComment count];
        NSString *totalComment = [NSString stringWithFormat:@"%d条评论", count];
        labelTotalComment.text = totalComment;
        
        [headerView addSubview:label];
        [headerView addSubview:labelTotalComment];
        [headerView setBackgroundColor:[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1]];
        
        return headerView;
    }else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return 30;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
#pragma mark -
#pragma mark Table view delegate



- (IBAction)doSendComment:(id)sender {
    
    if (textFieldComment.text.length == 0) {
        ALERT_ERR_MSG(@"请先写点评论吧！");
        return;
    }
    
    [self sendCommentData:textFieldComment.text];
}

- (void) getCommentData:(int) pageNo RefreshView:(MJRefreshBaseView *)refreshView {
    
    NSString *strPageNo = [NSString stringWithFormat:@"%d", pageNo];
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           findEntity.ID, @"travel_id",
                           strPageNo, @"page",
                           @"20", @"limit", nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_COMMENT
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"rows"];
                      if (pageNo == 1) {
                          [mutableArrayComment removeAllObjects];
                      }
                      for (NSDictionary* attributes in array) {
                          CommentEntity *entity = [[CommentEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [mutableArrayComment addObject:entity];
                      }
                      [self doneWithView:refreshView];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:refreshView];
                  }];
}

- (void) getFindData {
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           findEntity.ID, @"travel_id",
                           userEntity.userId,@"userid", nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_QUERY_BY_ID
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSDictionary *dic_data = [dic objectForKey:@"row"];
                      
                      findEntity = [findEntity initWithAttributes:dic_data];
                      if([findEntity.userid isEqualToString:USERID])
                      {
                          self.deleteBtn.hidden = NO;
                      }
                      [self doneWithView:nil];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [self doneWithView:nil];
                  }];
}

- (void) sendCommentData:(NSString *)content {
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           findEntity.ID, @"travel_id",
                           userEntity.userId, @"userid",
                           content, @"content", nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_SAVE_COMMENT
                  Successed:^(id entity) {
                      
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSNumber *code = [dic objectForKey:@"code"];
                      
                      if ([code intValue] == 0) {
                          CommentEntity *entity = [[CommentEntity alloc] init];
                          UserEntity *userEntity = [UserEntity sharedInstance];
                          
                          entity.ID = @"1";
                          entity.insert_time = [LPUtils getCurrentTime];
                          entity.content = textFieldComment.text;
                          entity.userid = userEntity.userId;
                          entity.userAlbum = userEntity.userAlbum;
                          entity.nickname = userEntity.nickName;
                          
                          [mutableArrayComment insertObject:entity atIndex:0];
                          [tableViewContent reloadData];
                          
                          textFieldComment.text = @"";
                      }
                      else if ([code intValue] == -101)
                      {
                          ALERT_ERR_MSG(@"您已经评论过当前景区");
                      }
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.textFieldComment) {
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.textFieldComment) {
        [textFieldComment resignFirstResponder];
    }
    return YES;
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.5 //速度0.7秒
                     animations:^{//修改坐标
                         viewComment.layer.transform = CATransform3DMakeTranslation(0, -height, 0);
                     }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    [UIView animateWithDuration:0.5 //速度0.7秒
                     animations:^{//修改坐标
                         viewComment.layer.transform = CATransform3DIdentity;
                     }];
}

- (void) shareAction:(NSInteger)tag {
        
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.delegate = self;
    HUD.labelText = Loading_Hard_Text;
    
    NSArray* imageArray = [[NSArray alloc] initWithObjects:[_imageViewBackground image], nil];
    
    [CommonService showShareActionSheet:self.view HUD:HUD
                             ImageArray:imageArray
                                    URL:PORTAL_URL
                                  Title:@"美图分享"
                                Content:findEntity.content];
}

- (void) zanAction:(NSInteger)tag {
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    [super showLoadingView:YES];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           findEntity.ID, @"travel_id",
                           userEntity.userId, @"userid",nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_GOOD
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      [self getFindData];
                      [super showLoadingView:NO];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [super showLoadingView:NO];
                  }];
}

- (void)addFooter {
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableViewContent;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        ++page;
        [self getCommentData:page RefreshView:refreshView];
        
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    _footer = footer;
}

- (void)addHeader {
    //__unsafe_unretained OAAnnoViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableViewContent;
    
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        // 进入刷新状态就会回调这个Block
        [self getFindData];
        [self getCommentData:page RefreshView:refreshView];
        NSLog(@"%@----开始进入刷新状态", refreshView.class);
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                NSLog(@"%@----切换到：普通状态", refreshView.class);
                break;
                
            case MJRefreshStatePulling:
                NSLog(@"%@----切换到：松开即可刷新的状态", refreshView.class);
                break;
                
            case MJRefreshStateRefreshing:
                NSLog(@"%@----切换到：正在刷新状态", refreshView.class);
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.tableViewContent reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void) enterZanListVC:(NSInteger)tag {
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    ZanListViewController *vc = [[ZanListViewController alloc] init];
    vc.findEntity = findEntity;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void) enterUserProfileVC:(NSInteger)tag {
    FindMeViewController *vc = [[FindMeViewController alloc] init];
    vc.userId = [NSString stringWithFormat:@"%d", (int)tag];
    [self.navigationController pushViewController:vc animated:YES];
}

//删除评论
- (void)deleteComment:(UIButton*)button
{
    //    NSLog(@"tag ======================= %d",button.tag);
    CommentEntity *entity = [mutableArrayComment objectAtIndex:button.tag];
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           USERID, @"user_id",
                           entity.ID, @"comment_id",
                           nil];
    
    [service getNetWorkData:param
                       Path:USER_TRAVEL_DELETE_COMMENT
                  Successed:^(id entity) {
                      
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSNumber *code = [dic objectForKey:@"code"];
                      
                      if ([code intValue] == 0) {
                          //                          CommentEntity *entity = [[CommentEntity alloc] init];
                          //                          UserEntity *userEntity = [UserEntity sharedInstance];
                          //
                          //                          entity.ID = @"1";
                          //                          entity.insert_time = [LPUtils getCurrentTime];
                          //                          entity.content = _textFieldComment.text;
                          //                          entity.userid = userEntity.userId;
                          //                          entity.album = userEntity.userAlbum;
                          //                          entity.nickname = userEntity.nickName;
                          
                          //                          [_mutableArrayComment insertObject:entity atIndex:0];
                          [mutableArrayComment removeObjectAtIndex:button.tag];
                          
                          NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:1];
                          [tableViewContent deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  withRowAnimation:UITableViewRowAnimationFade];
                          [tableViewContent reloadData];
                          
                          textFieldComment.text = @"";
                      }

                      else
                      {
                          ALERT_ERR_MSG(@"删除失败");
                      }
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      
                  }];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"FindDetailViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"FindDetailViewController"];
}

- (void) enterReportVC:(NSInteger)tag
{
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.login == NO) {
//        if (mainVC != nil) {
//            LoginViewController *vc = [[LoginViewController alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//        } else {
            LoginViewController *vc = [[LoginViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
//        }
        return;
    }
    
    ReportViewController *vc = [[ReportViewController alloc] init];
    vc.userId = userEntity.userId;
    vc.travel_id = findEntity.ID;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)deleteFind:(id)sender
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定要删除该游记？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [alert show];
    alert.delegate = self;
    alert.tag = 1001;


}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001)
    {
        if (buttonIndex == 0) {
            [self showLoadingView:YES];
            UserEntity *userEntity = [UserEntity sharedInstance];
            CommonService *service = [[CommonService alloc] init];
            NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                                   findEntity.ID, @"travel_id",
                                   userEntity.userId, @"user_id",nil];
            
            [service getNetWorkData:param
                               Path:USER_TRAVEL_DELETE
                          Successed:^(id entity) {
                              
                              NSDictionary *dic = (NSDictionary *)entity;
                              NSNumber *code = [dic objectForKey:@"code"];
                              [self showLoadingView:NO];
                              if ([code intValue] == 0)
                              {
                                  [self.navigationController popViewControllerAnimated:YES];
                                  [[NSNotificationCenter defaultCenter]postNotificationName:Activity_refresh object:nil];
                              }
                              else
                              {
                                  ALERT_ERR_MSG(@"删除失败");
                              }
                              
                          } Failed:^(NSInteger errorCode, NSString *message) {
                              [self showLoadingView:NO];
                              ALERT_ERR_MSG(@"删除失败");

                          }];
        }
    }
}

- (void)clickAtImage:(UIImageView *)imageView
{
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    imageInfo.image = imageView.image;
    
    imageInfo.referenceRect = imageView.frame;
    imageInfo.referenceView = imageView.superview;
    imageInfo.referenceContentMode = imageView.contentMode;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_None];
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
}

- (void)guanzhuAction:(NSInteger)tag
{
    
    UserEntity *userEntity = [UserEntity sharedInstance];
    
    if (userEntity.userId == nil) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        CommonService *service = [[CommonService alloc] init];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSString stringWithFormat:@"%d", (int)tag],@"attention_id",
                               userEntity.userId,@"userid",
                               nil];
        
        [service getNetWorkData:param
                           Path:USER_ATTENTION
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          NSNumber *code = [dic objectForKey:@"code"];
                          if ([code intValue] == 0) {
                              ALERT_ERR_MSG(@"关注成功");
                              [[NSNotificationCenter defaultCenter]postNotificationName:Notification_findview_refresh object:nil];
                              [self getFindData];
                          } else {
                              ALERT_ERR_MSG(@"关注失败");
                          }
                      } Failed:^(NSInteger errorCode, NSString *message) {
                      }];
    }
}


@end




